package com.liuhuan.controller;


import cn.hutool.core.util.StrUtil;
import com.liuhuan.api.CommonResult;
import com.liuhuan.entity.User;

import com.liuhuan.service.UserService;
import com.liuhuan.utils.JwtUtils;
import com.liuhuan.vo.LoginVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;


import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @version 1.0
 * @Author liuhuan
 * @Date 2024/7/4 15:12
 * @用户相关控制器
 */

@RestController
@RequestMapping("/user")
@Slf4j
@Api(tags = "用户管理模块")
public class UserController {
    @Autowired
    private UserService userService;
//    @Autowired
//    private RedisTemplate<String, Object> redisTemplate;
    @PostMapping(value="/login")
    @ApiOperation(value="用户登录")
    public CommonResult login(@RequestBody LoginVo loginVo){
//        String code = (String) redisTemplate.opsForValue().get("code");
//        if(loginVo.getCode()!=code){
//            return CommonResult.fail("验证码不对");
//        }
        if(StrUtil.isBlank(loginVo.getUsername())||StrUtil.isBlank(loginVo.getPassword())){
            return CommonResult.fail("数据输入不合法");
        }
        List<User> users = userService.login(loginVo);
        if(!users.isEmpty()){
            Map<String,Object> map=new HashMap<>();
            map.put("name",loginVo.getUsername());
            map.put("password",loginVo.getUsername());
            String s = JwtUtils.generateJwt(map);
            return CommonResult.success("登录成功",s);
        }
        else{
            return CommonResult.fail("用户名或密码不对");
        }
    }

    @PostMapping("/register")
    @ApiOperation(value = "用户注册")
    public CommonResult register(@RequestBody User user){
        Boolean flag = userService.register(user);
        if(flag){
            Map<String,Object> map=new HashMap<>();
            map.put("name",user.getUsername());
            map.put("password",user.getUsername());
            map.put("email",user.getEmail());
            String s = JwtUtils.generateJwt(map);
            return CommonResult.success("注册成功",s);
        }
        else{
            return CommonResult.fail("用户名重复");
        }

    }


}
